package cn.iocoder.yudao.module.system.dal.mysql.category;

import java.util.*;
import cn.iocoder.yudao.framework.mybatis.core.mapper.BaseMapperX;
import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.yudao.module.system.dal.dataobject.category.CategoryBooksDO;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;

/**
 * 绘本分类-绘本关联 Mapper
 *
 * @author 芋道源码
 */
@Mapper
public interface CategoryBooksMapper extends BaseMapperX<CategoryBooksDO> {

    /**
     * 批量插入关联记录
     */
    default int insertBatch(Long categoryId, List<Long> relatedIds, String type) {
        if (relatedIds == null || relatedIds.isEmpty()) {
            return 0;
        }
        List<CategoryBooksDO> categoryBooks = new ArrayList<>();
        for (Long relatedId : relatedIds) {
            CategoryBooksDO categoryBook = new CategoryBooksDO();
            categoryBook.setCategoryid(categoryId);
            categoryBook.setBookid(relatedId);
            categoryBook.setType(type);
            categoryBooks.add(categoryBook);
        }
        for (CategoryBooksDO categoryBook : categoryBooks) {
            insert(categoryBook);
        }
        return categoryBooks.size();
    }

    /**
     * 根据分类ID查询关联的绘本ID列表
     */
    default List<Long> selectBookIdsByCategoryId(Long categoryId) {
        return selectList(new LambdaQueryWrapperX<CategoryBooksDO>()
                .eq(CategoryBooksDO::getCategoryid, categoryId))
                .stream()
                .map(CategoryBooksDO::getBookid)
                .collect(java.util.stream.Collectors.toList());
    }

    /**
     * 根据分类ID删除关联记录
     */
    default int deleteByCategoryId(Long categoryId) {
        return delete(new LambdaQueryWrapperX<CategoryBooksDO>()
                .eq(CategoryBooksDO::getCategoryid, categoryId));
    }

    /**
     * 根据绘本ID删除关联记录
     */
    default int deleteByBookId(Long bookId) {
        return delete(new LambdaQueryWrapperX<CategoryBooksDO>()
                .eq(CategoryBooksDO::getBookid, bookId));
    }

    /**
     * 检查分类和绘本是否已关联
     */
    default boolean existsByCategoryIdAndBookId(Long categoryId, Long bookId) {
        return selectCount(new LambdaQueryWrapperX<CategoryBooksDO>()
                .eq(CategoryBooksDO::getCategoryid, categoryId)
                .eq(CategoryBooksDO::getBookid, bookId)) > 0;
    }

} 